package com.zlaidyrac.weride.ui;

import java.io.File;
import java.util.HashMap;

import com.zlaidyrac.weride.main.Common;
import com.zlaidyrac.weride.main.R;
import com.zlaidyrac.weride.persistence.SearchResult;
import com.zlaidyrac.weride.persistence.User;
import com.zlaidyrac.weride.webclient.WebClient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ViewMyRide extends Activity {
	public static final String FB_FRIEND_IMAGE_PATH = "weride/friend_fb_img.png";
	public static final int BUDDY_BUTTON_MODE_JOIN  = 1;
	public static final int BUDDY_BUTTON_MODE_JOINED = 2;
	String sfrom;
	String sto;
	int iseats;
	String sdate;
	String stime;
	String scost;
	String sdescription;
	
	Button ride_buddy_button;
	SearchResult carpool_details;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_viewmyride);
		carpool_details = Common.current_searchresult;
		TextView cost_per_head = (TextView)findViewById(R.id.cost);
		cost_per_head.setText(carpool_details.getCost_per_head());
		TextView from = (TextView)findViewById(R.id.fromTextView);
		from.setText(carpool_details.getFrm());
		TextView to = (TextView)findViewById(R.id.destinationTextView);
		to.setText(carpool_details.getDestination());
		
		new DownloadFbImageAsyncTask().execute();
		loadDriverData();
		if ( Common.rider_state == Common.RIDER_NOT_ADDED ) {
			modifyBuddyButton(BUDDY_BUTTON_MODE_JOIN);
		}
		else if ( Common.rider_state == Common.RIDER_ADDED ) {
			modifyBuddyButton(BUDDY_BUTTON_MODE_JOINED);
		}
	}
	public void loadDriverData() {
		TextView name = (TextView)findViewById(R.id.nameTextView);
		name.setText(carpool_details.getName());
		TextView email = (TextView)findViewById(R.id.emailTextView);
		email.setText(carpool_details.getEmail());
		TextView contact_no = (TextView)findViewById(R.id.contact_noTextView);
		contact_no.setText(carpool_details.getContact());
	}
	public void loadFbImage() {
		
		ImageView fbImageView = (ImageView) findViewById(R.id.driver_profpicImageView);
		fbImageView.setImageBitmap(BitmapFactory.decodeFile(
				Environment.getExternalStorageDirectory()+"/"+FB_FRIEND_IMAGE_PATH));
	}
	public void modifyBuddyButton(int mode) {
		ride_buddy_button = (Button)findViewById(R.id.ride_friend_interchangeableButton);
		switch ( mode ) {
		case BUDDY_BUTTON_MODE_JOIN:
			
			ride_buddy_button.setText("Ride");
			ride_buddy_button.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					HashMap<String,String> addRiderParams = new HashMap<String,String>();
					addRiderParams.put("availability_id", carpool_details.getAvailability_id());
					addRiderParams.put("rider_id", Common.loggedUser.getUserId());
					new JoinRideAsyncTask().execute(addRiderParams);
					modifyBuddyButton(BUDDY_BUTTON_MODE_JOINED);
					
				}
			});
			
			break;
		case BUDDY_BUTTON_MODE_JOINED:
			ride_buddy_button.setText("Already Joined");
			break;
		}
	}

	private class JoinRideAsyncTask extends AsyncTask<HashMap<String,String>, Void, Boolean> {
		protected ProgressDialog progressDialog;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = ProgressDialog.show(ViewMyRide.this, "Adding you as a rider", "Please wait...", true, false);
		}
		@Override
		protected Boolean doInBackground(HashMap<String, String>... params) {
			HashMap<String, String> result = WebClient.postRequest("add_rider", params[0]);
			if ( result.get("message").equals("error") ) {
				Log.e("ERROR", "Join ride request failed");
				return false;
			}
			else if ( result.get("message").equals("success") ) {
				return true;
			}
			return false;
		}
		protected void onPostExecute(Boolean success) {
			super.onPostExecute(success);
			progressDialog.dismiss();
			if ( success ) {
				
				Toast.makeText(getApplicationContext(), "You have joined this ride successfully", Toast.LENGTH_SHORT).show();
			}
			else {
				Toast.makeText(getApplicationContext(), "Failed to add to ride", Toast.LENGTH_SHORT).show();
			}
		}
		
	}
	private class DownloadFbImageAsyncTask extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected Boolean doInBackground(Void... params) {
			File f = new File(Environment.getExternalStorageDirectory()+"/"+FB_FRIEND_IMAGE_PATH);
			if ( !f.exists() ) {
				return true;
			}
			boolean decodeSuccess = WebClient.loadImageFromWebOperations(
					"http://graph.facebook.com/"
							+ Common.current_searchresult.getFb_url().trim()
							+ "/picture", Environment.getExternalStorageDirectory()+"/"+FB_FRIEND_IMAGE_PATH );
			
			return decodeSuccess;
		}
		protected void onPostExecute(Boolean success) {
			super.onPostExecute(success);
			if ( success ) {
				Log.i("Fb Image Load:", "Successful");
				loadFbImage();
			}
			else {
				Log.i("Fb Image Load:", "Fail");
			}
		}

	}
}
